<template>
  <BasicModal v-bind="$attrs" @register="registerModal" destroyOnClose :title="title" width="60%" @ok="handleSubmit">
    <a-row>
      <a-col span="24">
        <a-steps :current="current" class="steps-flow">
          <a-step v-for="item in steps" :key="item.title" :title="item.title" :description="item.description" />
        </a-steps>
        <div class="steps-content">
          <a-col span="12" style="margin: auto">
            <BasicForm @register="registerForm" />
          </a-col>
          <div class="ant-col ant-col-12" style="margin: auto" v-if="current == 1">
            <div class="ant-row ant-form-item" style="row-gap: 0px;margin-bottom: 4px;">
              <div class="ant-col ant-form-item-label" style="width: 120px;">
              </div>
              <div class="ant-col ant-col-xs-24 ant-col-sm-18 ant-form-item-control sousuo"
                style="width: calc(100% - 120px);">
                <a-input v-model="keyword" placeholder="请输入搜索生产标准关键字" type="text" id="" class="ant-input"
                  @change="changeWord" @pressEnter="searchWord" />
                <div class="ss_icon" @click="searchWord">
                  <img class="ss_icon_img" src="/icn_ss.png" alt="">
                </div>
              </div>
            </div>
            <div class="ant-row ant-form-item" style="row-gap: 0px;">
              <div class="ant-col ant-form-item-label" style="width: 120px;">
                <label for="form_item_operationDescription" class="">
                  生产标准
                </label>
              </div>
              <div class="ant-col ant-col-xs-24 ant-col-sm-18 ant-form-item-control" style="width: calc(100% - 120px);">
                <ul class="scbz_list">
                  <li id="scbz_item" v-for="(item, index) in scbz_arr" :class="item.selected ? 'scbz_item_active' : ''"
                    :key="item.title" @click="choice(index)">{{ item.title }}</li>
                </ul>
              </div>
            </div>
          </div>
        </div>
      </a-col>
    </a-row>
    <template #footer>
      <div class="steps-action">
        <a-button v-if="current > 0" style="margin-right: 8px" @click="prev">上一步</a-button>
        <a-button v-if="current < steps.length - 1" type="primary" @click="next">下一步</a-button>
        <a-button v-if="current == steps.length - 1" type="primary" @click="handleSubmit">
          提交
        </a-button>
      </div>
    </template>
  </BasicModal>
</template>

<script lang="ts" setup>
import { ref, computed, unref, nextTick, watch, watchEffect, reactive } from 'vue';
import { BasicModal, useModalInner } from '/@/components/Modal';
import { BasicForm, useForm } from '/@/components/Form/index';
import { formSchema } from '../TProductionSchedule.data';
import { saveOrUpdate, createProductionScheduleByTemplateId } from '../TProductionSchedule.api';
import { list } from "/@/views/planting-process/productionScheduleTemplate/ProductionScheduleTemplate.api";
import { defHttp } from "/@/utils/http/axios";


// Emits声明
const emit = defineEmits(['register', 'success']);
const isUpdate = ref(true);

// 步骤条配置
const current = ref<number>(0);
const next = () => {
  validateForm(true);
};
const prev = () => {
  current.value--;
};

const validateForm = (type) => {
  let valid;
  switch (current.value) {
    case 0:
      valid = validateFields(['growPlanId', 'productionOperation']);
      break;
    case 1:
      valid = validateFields(['input', 'operationDescription']);
      break;
    case 2:
      valid = validateFields(['jobStartTime', 'jobUsers']);
      break;
  }
  valid.then(values => {
    type ? current.value++ : current.value--;
  }).catch(err => {
    console.log(err)
  })
}

// 分别展示表单项
watch(current, (v) => {
  switch (v) {
    case 0:
      hiddenField(['growPlanId', 'productionOperation']);
      break;
    case 1:
      getProductionStandard();
      hiddenField(['input', 'operationDescription']);
      break;
    case 2:
      hiddenField(['jobStartTime', 'jobUsers']);
      break;
  }
})
const scbz_arr = ref();
const getProductionStandard = (word: string) => {
  const formData = getFieldsValue();
  if (formData.growPlanId && formData.productionOperation) {
    defHttp.get({
      url: "/productionStandard/getStandByProductionOperationAndGrowPlan", params: {
        growPlanId: formData.growPlanId,
        productionOperation: formData.productionOperation,
        keyWord: word || ''
      }

    }).then(res => {
      scbz_arr.value = [];
      res.records.map(item => {
        scbz_arr.value.push({
          title: item.content,
          selected: false
        })
      })
    })
  }
}

const keyword = ref();
const changeWord = (e) => {
  keyword.value = e.target.value;
}
const searchWord = () => {
  getProductionStandard(keyword.value)
}

const hiddenField = (fields, render = 1) => {
  formSchema.map((item) => {
    if (fields.includes(item.field)) {
      render ? updateSchema({ field: item.field, show: true }) : item.show = true;
    } else {
      render ? updateSchema({ field: item.field, show: false }) : item.show = false;
    }
  })
}
const choice = (index) => {
  scbz_arr.value[index].selected = !scbz_arr.value[index].selected
  let content = getFieldsValue().operationDescription || '';
  if (scbz_arr.value[index].selected) {
    content += scbz_arr.value[index].title
  } else {
    content = content.replace(scbz_arr.value[index].title, '');
  }
  setFieldsValue({ operationDescription: content })
}

const steps = [
  {
    title: '做什么？',
    description: '选择农事类型',
    content: 'First-content',
  },
  {
    title: '有无投入品？',
    description: '选投入品',
    content: 'Second-content',
  },
  {
    title: '任务分工',
    description: '指派人和时间',
    content: 'Last-content',
  },
];
const items = steps.map(item => ({ key: item.title, title: item.title }));

const cardData = ref([]);
const pagination = {
  total: 0,
  showQuickJumper: true,
  onChange: (page: number) => {
    pageList({ pageSize: 5, pageNo: page })
  },
  pageSize: 5,
};

hiddenField(['growPlanId', 'productionOperation'], 0);

formSchema.map((item) => {
  if (item.field == 'productionOperation') {
    item.componentProps.onchange = (e) => {
      console.log(e)
    }
  }
})

//表单配置
const [registerForm, { setProps, resetFields, setFieldsValue, validate, updateSchema, validateFields, getFieldsValue }] = useForm({
  labelWidth: 120,
  schemas: formSchema,
  showActionButtonGroup: false,
  baseColProps: { span: 24 }
});

//表单赋值
const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
  if (data && data.record) {
    data.record.growPlanId = data.record.growPlanId.toString();
  }
  //重置表单
  await resetFields();
  setModalProps({ confirmLoading: false, showCancelBtn: !!data?.showFooter, showOkBtn: !!data?.showFooter });
  isUpdate.value = !!data?.isUpdate;
  current.value = data?.current || 0
  if (unref(isUpdate)) {
    //表单赋值
    await setFieldsValue({
      ...data.record,
    });
  } else {
    pageList({ pageSize: 5, pageNo: 1 })
  }
  // 隐藏底部时禁用整个表单
  setProps({ disabled: !data?.showFooter })
});
//设置标题
const title = computed(() => (!unref(isUpdate) ? '新增' : '编辑'));
//表单提交事件
async function handleSubmit(v) {
  try {
    let values = await validate();
    values.jobUsers = values.jobUsers.split(',')
    setModalProps({ confirmLoading: true });
    //提交表单
    await saveOrUpdate(values, isUpdate.value);
    //关闭弹窗
    closeModal();
    //刷新列表
    emit('success');
  } finally {
    setModalProps({ confirmLoading: false });
  }
}
async function pageList(page) {
  list(page).then(res => {

    cardData.value = res.records;
    pagination.total = res.total;
  })
}


async function handleClick(item) {
  // 这里是你处理点击事件的代码
  createProductionScheduleByTemplateId({ templateId: item.id })
    .then(async res => {
      await nextTick();
      await resetFields();
      await setFieldsValue({ ...res })
    })
}
</script>

<style lang="less">
.scbz_list {
  display: flex;
  flex-wrap: wrap;

}

#scbz_item {
  margin: 5px;
  line-height: 36px;
  padding: 0px 15px;
  background: #fff;
  color: rgba(0, 0, 0, 0.6);
  border: 1px solid #E5E7EB;
  box-sizing: border-box;
  border-radius: 4px;
  cursor: pointer;
  transition: border-color .5s;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

#scbz_item:hover {
  // background: rgba(64, 169, 255, 0.2) !important;
  border: 1px solid #40a9ff !important;
  color: #40a9ff !important;
  box-shadow: 0px 2px 2px rgba(24, 144, 255, 0.25);
}

.scbz_item_active {
  // background: rgba(64, 169, 255, 0.2) !important;
  border: 1px solid #40a9ff !important;
  color: #40a9ff !important;
}

.steps-flow {
  width: 75%;
  margin: 30px auto;
}

/** 时间和数字输入框样式 */
:deep(.ant-input-number) {
  width: 100%
}

:deep(.ant-calendar-picker) {
  width: 100%
}

// 步骤条样式
.steps-content {
  margin-top: 16px;
  border: 1px dashed #e9e9e9;
  border-radius: 6px;
  background-color: #fafafa;
  min-height: 200px;
  // text-align: center;
  padding-top: 80px;
  min-height: 500px;
}

.steps-action {
  margin-top: 24px;
  text-align: right;
}

.sousuo {
  position: relative;

  .ss_icon {
    position: absolute;
    height: 70%;
    width: 50px;
    top: 50%;
    right: 0;
    bottom: 0;
    border-left: 1px solid #eee;
    transform: translateY(-50%);
    cursor: pointer;
  }

  .ss_icon_img {
    width: 20px;
    height: 20px;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
  }
}

[data-theme='dark'] .steps-content {
  background-color: #2f2f2f;
  border: 1px dashed #404040;
}

@media (max-width: 1550px) {
  .steps-flow {
    width: 100%;
    margin: 30px auto;
  }
}

html,
body {
  font-family: PingFang SC;
}
</style>
